package com.isc.tcpCommunicationReview;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        //服务器端监听ip和端口号
        int port = 9999;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("正在监听" + port + "端口...");

        //已连接套接字
        Socket accept = serverSocket.accept();
        System.out.println("已建立连接...");

        //接收客户端发送的信息
        InputStream inputStream = accept.getInputStream();
        //将字节流转换成字符流
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String s = br.readLine();
        System.out.println("接收到客户端发送的消息是:"+s);

        //接收到客户端消息后，回发一个消息
        OutputStream outputStream = accept.getOutputStream();
        //将字节流转换成字符流
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write("hello,client~");
        bw.newLine();//结束符，表示信息已经发送完了
        bw.flush();//手动刷新，不然消息发不出去
        System.out.println("服务器发送消息成功...");

        //关闭资源
        bw.close();
        br.close();
        accept.close();
        serverSocket.close();
        System.out.println("与客户端断开连接");
    }
}
